//
//  LoginViewController.m
//  JunZeWristband
//
//  Created by Kendama on 2017/8/16.
//  Copyright © 2017年 DT. All rights reserved.
//

#import "LoginViewController.h"
#import "LoginView.h"
#import "RegisterViewController.h"
#import "ForgetPasswordViewController.h"
#import "PublicLoginApi.h"
#import "PublicGetUserInfoApi.h"
#import "PublicTheThirdLoginApi.h"
#import "ModifyUserInformation.h"

@interface LoginViewController ()

@property(nonatomic,strong) LoginView *containerView;
@property(nonatomic,strong) RegisterViewController *registerVC;
@property(nonatomic,strong) ForgetPasswordViewController *forgetVC;


@end

@implementation LoginViewController

#pragma mark - view lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.containerView.phoneView.phoneTextField resignFirstResponder];
    [self.containerView.passwordView.passwordTextField resignFirstResponder];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    
}

- (void)refreshBaseControlValue
{
    
}

#pragma mark - 点击事件
- (void)didClickRegisterButton
{
//    [self.navigationController pushViewController:self.registerVC animated:YES];
    RegisterViewController *vc = [[RegisterViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didClickLoginButton
{
    if (![self.containerView.phoneView.phoneTextField.text isMobileNumber]) {
        
        [SVProgressHUD showErrorWithStatus:MyNSLocalizedString(@"请输入正确的手机号码..")];
        return;
    }
    
    if (![self.containerView.passwordView.passwordTextField.text isRegexPassword]) {
        [SVProgressHUD showErrorWithStatus:MyNSLocalizedString(@"请输入符合规定的密码")];
        return;
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showInfoWithStatus:MyNSLocalizedString(@"正在登录...")];
    });
    
    [self loginActionStart];
//    SAVE_OBJECT(@"YES", LOGIN);
}

// 开始登录
- (void)loginActionStart {
    
    PublicLoginApi *api = [[PublicLoginApi alloc]initWithDic:@{@"username":self.containerView.phoneView.phoneTextField.text,@"password":self.containerView.passwordView.passwordTextField.text}];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dict = [request responseJSONObject];
        if ([dict[@"errcode"] intValue] == 0) {
            
            [SVProgressHUD showSuccessWithStatus:MyNSLocalizedString(@"您已安全登录！")];
            SAVE_OBJECT(self.containerView.phoneView.phoneTextField.text , USERNAME);
            SAVE_OBJECT(self.containerView.passwordView.passwordTextField.text, PASSWORD);
            SAVE_OBJECT(dict[@"data"][@"uid"], UID);
            SAVE_OBJECT(dict[@"data"][@"token"], TOKEN);
            SAVE_OBJECT(dict[@"data"][@"image"], IMAGE);
            SAVE_OBJECT(@"YES", @"Login");   // 登录状态保存来设置根控制器
            SAVE_OBJECT(@"YES", LOGIN);
            
            [NSThread sleepForTimeInterval:0.5];
            [[AppDelegate defaultService] setRootViewController];

//            NSString *registrationID = DTCEXRACT_OBJECT(@"RegistrationID");
//            if ([DTCEXRACT_OBJECT(LOGIN) isEqualToString:@"YES"]) {
//                JPushUploadDeviceTokenAPI * api = [[JPushUploadDeviceTokenAPI alloc] initWithToken:registrationID];
//                [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
//                    [api analyseResponseObject];
//                } failure:^(YTKBaseRequest *request) {
//                    NSLog(@"上传极光失败");
//                }];
//            }
            
            [self GetUserInfo];
        } else {
            [SVProgressHUD showInfoWithStatus:dict[@"errmsg"]];
        }
    } failure:^(YTKBaseRequest *request) {
        [SVProgressHUD showInfoWithStatus:MyNSLocalizedString(@"网络有误")];
    }];
}



- (void)didClickForgetButton
{
//    [self.navigationController pushViewController:self.forgetVC animated:YES];
    ForgetPasswordViewController *vc = [[ForgetPasswordViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didClickQQButton
{
    [DTCSharePlatformManager qqLoginSuccess:^(SSDKUser *user) {
        [self theThirdLoginWithOpenId:user.uid andType:@"1" andModifyInformationWithSex:[NSString stringWithFormat:@"%lu",(unsigned long)user.gender+1] andNickname:user.nickname andIcon:user.icon];
    } fail:^{
        
    }];
}

- (void)didClickWechatButton
{
    [DTCSharePlatformManager wechartLoginSuccess:^(SSDKUser *user) {
        [self theThirdLoginWithOpenId:user.rawData[@"unionid"] andType:@"2" andModifyInformationWithSex:[NSString stringWithFormat:@"%lu",(unsigned long)user.gender+1] andNickname:user.nickname andIcon:user.icon];
    } fail:^{
        
    }];
}

- (void)didClickWeiboButton
{
    [DTCSharePlatformManager weiboLoginSuccess:^(SSDKUser *user) {
        [self theThirdLoginWithOpenId:user.uid andType:@"3" andModifyInformationWithSex:[NSString stringWithFormat:@"%lu",(unsigned long)user.gender+1] andNickname:user.nickname andIcon:user.icon];
    } fail:^{
        
    }];
}

- (void)theThirdLoginWithOpenId:(NSString *)openid andType:(NSString *)loginType andModifyInformationWithSex:(NSString *)sex andNickname:(NSString *)nickname andIcon:(NSString *)icon
{
//    [[DTCloudManager defaultJNI_iOS_SDK] loginWithThirdOpenId:openid successCallback:^(NSDictionary *dic) {
        PublicTheThirdLoginApi *loginApi = [[PublicTheThirdLoginApi alloc]initWithDic:@{@"openid":openid,@"type":loginType}];
        [loginApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            //保存数据
            NSDictionary * dict = [loginApi responseJSONObject];
            NSLog(@"dict = %@",dict[@"errmsg"]);
            if ([dict[@"errcode"] intValue] == 0) {
                SAVE_OBJECT(dict[@"data"][@"uid"], UID);
                SAVE_OBJECT(dict[@"data"][@"token"], TOKEN);
                //            NSLog(@"login = %@",EXRACT_OBJECT(LOGINING));
                //修改用户信息
                [self modifyUserInformationWithSex:sex andNickname:nickname andIcon:icon andFirst:[dict[@"data"][@"is_first_login"] boolValue]];
                NSLog(@"第三方第一次登陆标志：%@",dict[@"data"][@"is_first_login"]);
                
            } else {
                [SVProgressHUD showErrorWithStatus:dict[@"errmsg"]];
            }
            
            
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            NSLog(@"%@",request.error);
            [SVProgressHUD showErrorWithStatus:MyNSLocalizedString(@"登陆失败！")];
        }];
//    } errorCallback:^(NSDictionary *dic) {
//        [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];
//    }];
    
    
}

//修改用户信息
- (void)modifyUserInformationWithSex:(NSString *)sex andNickname:(NSString *)nickname andIcon:(NSString *)icon andFirst:(BOOL)first
{
    if (first) {
        UIImageView *imageView = [[UIImageView alloc]init];
        [[AppDelegate defaultService].window addSubview:imageView];
        imageView.hidden = YES;
        [imageView sd_setImageWithURL:[NSURL URLWithString:icon] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            [UIImageJPEGRepresentation(image, 0.5f) writeToFile:PorPath atomically:YES];
            
            ModifyUserInformation *modifyApi = [[ModifyUserInformation alloc]initWithDic:@{@"nickname":nickname,@"sex":sex,@"image":PorPath}];
            [modifyApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
                
                NSDictionary *dic = [modifyApi responseJSONObject];
                NSLog(@"errcode dic = %@",dic[@"errmsg"]);
                if([dic[@"errcode"] intValue] == 0) {
                    [SVProgressHUD showSuccessWithStatus:MyNSLocalizedString(@"用户登陆成功")];
                    SAVE_OBJECT(@"YES", LOGIN);   // 登录状态保存来设置根控制器
                    SAVE_OBJECT(sex, SEX);
                    SAVE_OBJECT(nickname, NICKNAME);
                    SAVE_OBJECT(icon, IMAGE);
                    [SVProgressHUD dismiss];
                    //跳转主页
                    [[AppDelegate defaultService] setRootViewController];
                } else {
                    [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];
                }
                
            } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
                
                [SVProgressHUD showErrorWithStatus:@"请求失败"];
            }];

        }];

    }else{
        SAVE_OBJECT(icon, IMAGE);
        SAVE_OBJECT(@"YES", LOGIN);   // 登录状态保存来设置根控制器
        [[AppDelegate defaultService]setRootViewController];
    }
}


#pragma mark - 事件处理
- (void)GetUserInfo {
    
    PublicGetUserInfoApi * userInfoApi = [[PublicGetUserInfoApi alloc] init];
    [userInfoApi startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [userInfoApi analyseResponseObject];
        SAVE_OBJECT(@"YES", LOGIN);
        [[AppDelegate defaultService]setRootViewController];
    } failure:^(YTKBaseRequest *request) {
        [SVProgressHUD showErrorWithStatus:@"获取用户信息失败！"];
    }];
}

#pragma mark - 代理


#pragma mark - 通知处理

#pragma mark - 初始化
- (RegisterViewController *)registerVC
{
    if(!_registerVC)
    {
        _registerVC = [[RegisterViewController alloc]init];
    }
    return _registerVC;
}

- (ForgetPasswordViewController *)forgetVC
{
    if(!_forgetVC)
    {
        _forgetVC = [[ForgetPasswordViewController alloc]init];
    }
    return _forgetVC;
}


- (LoginView *)containerView
{
    if(!_containerView)
    {
        UIView *superView = self.view;
        _containerView = [[LoginView alloc]init];
        [superView addSubview:_containerView];
        [_containerView.registerButton addTarget:self action:@selector(didClickRegisterButton) forControlEvents:UIControlEventTouchUpInside];
        [_containerView.forgetButton addTarget:self action:@selector(didClickForgetButton) forControlEvents:UIControlEventTouchUpInside];
        [_containerView.loginButton addTarget:self action:@selector(didClickLoginButton) forControlEvents:UIControlEventTouchUpInside];
        [_containerView.qqButton addTarget:self action:@selector(didClickQQButton) forControlEvents:UIControlEventTouchUpInside];
        [_containerView.wechatButton addTarget:self action:@selector(didClickWechatButton) forControlEvents:UIControlEventTouchUpInside];
        [_containerView.weiboButton addTarget:self action:@selector(didClickWeiboButton) forControlEvents:UIControlEventTouchUpInside];

    }
    return _containerView;
}


- (void)setNavigationStyle
{
    [self hideNavigationBar];
    self.navigationBar.backgroundColor = [UIColor clearColor];
    [self hideNavigationBottomLine];
}

- (void)masLayoutSubview
{
    __weak UIView *superView = self.view;
    [self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(superView);
    }];
}


@end
